const db = require('../config/database')
const { success, error } = require('../utils/responseHelper')
const { isDateInRange } = require('../utils/dateHelper')

const examController = {
  // 获取考试列表
  async getExams(req, res, next) {
    try {
      const { role, id: userId } = req.user
      const { status, page = 1, limit = 10 } = req.query

      const offset = (page - 1) * limit

      let query = `
        SELECT e.*, 
               COUNT(DISTINCT q.id) as question_count,
               COUNT(DISTINCT er.id) as participant_count,
               u.name as creator_name
        FROM exams e 
        LEFT JOIN questions q ON e.id = q.exam_id
        LEFT JOIN exam_records er ON e.id = er.exam_id
        LEFT JOIN users u ON e.created_by = u.id
      `

      const conditions = []
      const params = []

      if (role === 'student') {
        conditions.push("e.status = 'published'")

        // 如果指定了状态筛选
        if (status === 'available') {
          conditions.push('e.start_time <= NOW() AND e.end_time >= NOW()')
        } else if (status === 'finished') {
          conditions.push('e.end_time < NOW()')
        } else if (status === 'upcoming') {
          conditions.push('e.start_time > NOW()')
        }
      } else if (role === 'admin') {
        if (status) {
          conditions.push('e.status = ?')
          params.push(status)
        }
      }

      if (conditions.length > 0) {
        query += ' WHERE ' + conditions.join(' AND ')
      }

      query += ' GROUP BY e.id ORDER BY e.created_at DESC LIMIT ? OFFSET ?'
      params.push(parseInt(limit), offset)

      const [exams] = await db.execute(query, params)

      // 如果是学生，添加参与状态
      if (role === 'student' && exams.length > 0) {
        const examIds = exams.map((exam) => exam.id)
        const [records] = await db.execute(
          `SELECT exam_id, status, total_score, end_time 
           FROM exam_records 
           WHERE exam_id IN (${examIds
             .map(() => '?')
             .join(',')}) AND user_id = ?`,
          [...examIds, userId]
        )

        const recordMap = records.reduce((acc, record) => {
          acc[record.exam_id] = record
          return acc
        }, {})

        exams.forEach((exam) => {
          exam.user_record = recordMap[exam.id] || null
        })
      }

      // 获取总数
      let countQuery = 'SELECT COUNT(DISTINCT e.id) as total FROM exams e'
      if (conditions.length > 0) {
        countQuery += ' WHERE ' + conditions.join(' AND ')
      }

      const [countResult] = await db.execute(countQuery, params.slice(0, -2))
      const total = countResult[0].total

      success(res, {
        exams,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit),
        },
      })
    } catch (err) {
      next(err)
    }
  },

  // 获取考试详情
  async getExam(req, res, next) {
    try {
      const { id } = req.params
      const { role, id: userId } = req.user

      const [exams] = await db.execute(
        `
        SELECT e.*, u.name as creator_name,
               COUNT(DISTINCT q.id) as question_count,
               COUNT(DISTINCT er.id) as participant_count
        FROM exams e 
        LEFT JOIN users u ON e.created_by = u.id
        LEFT JOIN questions q ON e.id = q.exam_id
        LEFT JOIN exam_records er ON e.id = er.exam_id
        WHERE e.id = ?
        GROUP BY e.id
      `,
        [id]
      )

      if (exams.length === 0) {
        return error(res, '考试不存在', 404)
      }

      const exam = exams[0]

      // 权限检查
      if (role === 'student' && exam.status !== 'published') {
        return error(res, '考试未发布', 403)
      }

      // 获取学生的考试记录
      if (role === 'student') {
        const [records] = await db.execute(
          'SELECT * FROM exam_records WHERE exam_id = ? AND user_id = ?',
          [id, userId]
        )
        exam.user_record = records[0] || null
      }

      success(res, exam)
    } catch (err) {
      next(err)
    }
  },

  // 创建考试
  async createExam(req, res, next) {
    try {
      const {
        title,
        description,
        duration,
        total_score,
        start_time,
        end_time,
      } = req.body
      const created_by = req.user.id

      // 验证时间
      if (new Date(start_time) >= new Date(end_time)) {
        return error(res, '开始时间必须早于结束时间', 400)
      }

      const [result] = await db.execute(
        `
        INSERT INTO exams (title, description, duration, total_score, start_time, end_time, created_by) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
      `,
        [
          title,
          description,
          duration,
          total_score,
          start_time,
          end_time,
          created_by,
        ]
      )

      success(
        res,
        {
          id: result.insertId,
          title,
          description,
          duration,
          total_score,
          start_time,
          end_time,
          status: 'draft',
        },
        '考试创建成功'
      )
    } catch (err) {
      next(err)
    }
  },

  // 更新考试
  async updateExam(req, res, next) {
    try {
      const { id } = req.params
      const {
        title,
        description,
        duration,
        total_score,
        start_time,
        end_time,
        status,
      } = req.body

      // 检查考试是否存在
      const [exams] = await db.execute('SELECT * FROM exams WHERE id = ?', [id])
      if (exams.length === 0) {
        return error(res, '考试不存在', 404)
      }

      // 验证时间
      if (
        start_time &&
        end_time &&
        new Date(start_time) >= new Date(end_time)
      ) {
        return error(res, '开始时间必须早于结束时间', 400)
      }

      // 如果要发布考试，检查是否有题目
      if (status === 'published') {
        const [questions] = await db.execute(
          'SELECT COUNT(*) as count FROM questions WHERE exam_id = ?',
          [id]
        )
        if (questions[0].count === 0) {
          return error(res, '请先添加题目后再发布考试', 400)
        }
      }

      const updateFields = []
      const updateValues = []

      if (title !== undefined) {
        updateFields.push('title = ?')
        updateValues.push(title)
      }
      if (description !== undefined) {
        updateFields.push('description = ?')
        updateValues.push(description)
      }
      if (duration !== undefined) {
        updateFields.push('duration = ?')
        updateValues.push(duration)
      }
      if (total_score !== undefined) {
        updateFields.push('total_score = ?')
        updateValues.push(total_score)
      }
      if (start_time !== undefined) {
        updateFields.push('start_time = ?')
        updateValues.push(start_time)
      }
      if (end_time !== undefined) {
        updateFields.push('end_time = ?')
        updateValues.push(end_time)
      }
      if (status !== undefined) {
        updateFields.push('status = ?')
        updateValues.push(status)
      }

      updateFields.push('updated_at = NOW()')
      updateValues.push(id)

      await db.execute(
        `
        UPDATE exams SET ${updateFields.join(', ')} WHERE id = ?
      `,
        updateValues
      )

      success(res, null, '考试更新成功')
    } catch (err) {
      next(err)
    }
  },

  // 删除考试
  async deleteExam(req, res, next) {
    try {
      const { id } = req.params

      // 检查是否有学生已经参加考试
      const [records] = await db.execute(
        'SELECT COUNT(*) as count FROM exam_records WHERE exam_id = ?',
        [id]
      )

      if (records[0].count > 0) {
        return error(res, '已有学生参加考试，无法删除', 400)
      }

      const [result] = await db.execute('DELETE FROM exams WHERE id = ?', [id])

      if (result.affectedRows === 0) {
        return error(res, '考试不存在', 404)
      }

      success(res, null, '考试删除成功')
    } catch (err) {
      next(err)
    }
  },

  // 获取考试统计
  async getExamStats(req, res, next) {
    try {
      const { id } = req.params

      // 基本统计
      const [basicStats] = await db.execute(
        `
        SELECT 
          COUNT(DISTINCT er.user_id) as total_participants,
          COUNT(CASE WHEN er.status = 'submitted' THEN 1 END) as completed_count,
          COUNT(CASE WHEN er.status = 'in_progress' THEN 1 END) as in_progress_count,
          AVG(CASE WHEN er.status = 'submitted' THEN er.total_score END) as avg_score,
          MAX(CASE WHEN er.status = 'submitted' THEN er.total_score END) as max_score,
          MIN(CASE WHEN er.status = 'submitted' THEN er.total_score END) as min_score
        FROM exam_records er 
        WHERE er.exam_id = ?
      `,
        [id]
      )

      // 分数段统计
      const [scoreDistribution] = await db.execute(
        `
        SELECT 
          COUNT(CASE WHEN total_score >= 90 THEN 1 END) as excellent,
          COUNT(CASE WHEN total_score >= 80 AND total_score < 90 THEN 1 END) as good,
          COUNT(CASE WHEN total_score >= 70 AND total_score < 80 THEN 1 END) as average,
          COUNT(CASE WHEN total_score >= 60 AND total_score < 70 THEN 1 END) as pass,
          COUNT(CASE WHEN total_score < 60 THEN 1 END) as fail
        FROM exam_records 
        WHERE exam_id = ? AND status = 'submitted'
      `,
        [id]
      )

      success(res, {
        basic: basicStats[0],
        distribution: scoreDistribution[0],
      })
    } catch (err) {
      next(err)
    }
  },
}

module.exports = examController
